<template>
  <div class="parent">
    <div class="top">
      <div v-show="name" style="float: left;margin-left: 10px">姓名：{{name}}</div>
      <div v-show="mj" style="float: left;margin-left: 10px">地块面积(亩)：{{mj}}</div>
      <div @click="returnClick" style="float: right;margin-right: 10px">施肥建议></div>
    </div>
    <div id="map"></div>
  </div>
</template>

<script>
  import mapboxgl from 'mapbox-gl';
  import turf from '@turf/bbox';
  import API from './../api/api_user';
  import layerSrc from '../config/layer_identify';

  export default {
    name: 'TestMap',
    data() {
      return {
        map: null,
        hasLoaded: false,
        showInfo: false,
        id: null,
        qhmc: null,
        zwmc: null,
        name: '',
        mj: 0
      };
    },
    mounted() {
      if (!mapboxgl.supported()) {
        window.android.report();
        alert('Your browser does not support Mapbox GL');
      }
      mapboxgl.accessToken = 'pk.eyJ1IjoiaGFtYnVnZXJkZXZlbG9wIiwiYSI6ImNqNXJtZjF4ZzB3em4yd21pZmVqbHlleDAifQ.I9eqVjtotz7jaU7XcJm9pQ';
      this.map = new mapboxgl.Map({
        container: 'map',
        // style:'http://gykj123.cn:9035/api/v1/styles/gykj/rygaxrHmWB',
        // style: 'https://gykj.com.cn/api/v1/styles/gykj/S1wsBE2lH',
        style:'./static/style.json',
        center: [114.08316983, 33.615693],
        zoom: 8
      });

      const that = this;
      this.map.on('style.load', function() {
        //添加高亮图层
        if (!that.hasLoaded) {
          that.hasLoaded = true;


          that.map.on('moveend',function (e) {
            if(e.moveend&&e.moveend=="111"){
              that.initHeightAndFilter();
            }
          });
          //添加点击图层
          that.map.addLayer({
            "id": "种植地块点击",
            "source": "dt_zzdk",
            "type": "fill",
            "minzoom": 13,
            "maxzoom": 18,
            "layout": {
              "visibility": "visible"
            },
            "paint": {
              "fill-color": "#00ff00",
              "fill-opacity": 0,
            },
            "source-layer": "dt_zzdk",
            "metadata": {
              "mapbox:group": "3ad046ebc0f3b"
            }
          });
          //添加高亮图层
          that.map.addLayer({
            'id': '种植地块高亮',
            'source': 'dt_zzdk',
            'type': 'line',
            'minzoom': 1,
            'maxzoom': 23,
            'layout': {
              'visibility': 'visible'
            },
            'paint': {
              'line-color': '#00ffff',
              'line-width': 5
            },
            'source-layer': 'dt_zzdk',
            'metadata': {
              'mapbox:group': '04687df45bbae'
            },
            'visibility': 'visible',
            'filter': [
              'in',
              'objectid',
              ''
            ]
          });
          //显示村数据
          if (that.getQueryString('qhdm')) {
            that.map.setLayoutProperty('种植地块', 'visibility', 'visible');
            that.map.setLayoutProperty('种植结构', 'visibility', 'visible');
            that.map.setLayoutProperty('农情信息', 'visibility', 'none');

            that.map.setLayoutProperty('采样点信息', 'visibility', 'none');

            let qhdm = that.getQueryString('qhdm');

            that.locateXzqByQhdm(qhdm);
            that.map.setFilter('种植结构', ['==', 'qhdm', qhdm]);
            that.map.setFilter('种植地块', ['==', 'qhdm', qhdm]);
            that.map.setFilter('种植地块点击', ['==', 'qhdm', qhdm]);

            that.map.setFilter('村域', ['==', 'qhdm', qhdm]);
            that.map.setFilter('村点', ['==', 'qhdm', qhdm]);
            that.map.setFilter('种植标注', ['==', 'qhdm', qhdm]);
          }

          that.addControl();
          // 点击查询
            that.map.on('click', '种植地块点击', function(e) {
            let bbox = [[e.point.x, e.point.y], [e.point.x, e.point.y]];
            let features = that.map.queryRenderedFeatures(bbox, {layers: ['种植地块点击']});
            if (features.length > 0) {
              let filter = features.reduce(function(memo, feature) {
                memo.push(feature.properties.objectid);
                return memo;
              }, ['in', 'objectid']);
              let coordinates = features[0].geometry.coordinates[0];
              let lngMin = coordinates[0][0];
              let lngMax = coordinates[0][0];
              let latMin = coordinates[0][1];
              let latMax = coordinates[0][1];
              for (let i = 1; i < coordinates.length; i++) {
                if (lngMin > coordinates[i][0]) {
                  lngMin = coordinates[i][0];
                } else if (lngMax < coordinates[i][0]) {
                  lngMax = coordinates[i][0];
                }
                if (latMin > coordinates[i][1]) {
                  latMin = coordinates[i][1];
                } else if (lngMax < coordinates[i][1]) {
                  latMax = coordinates[i][1];
                }
              }

              that.map.fitBounds(new mapboxgl.LngLatBounds([lngMin, latMin], [lngMax, latMax]), {
                padding: 60
              });


              that.showInfo = true;
              that.id = features[0].properties.objectid;
              console.log(features[0].properties);
              that.qhmc = features[0].properties.qhmc;
              that.zwmc = features[0].properties.zwmc;
              that.map.setFilter('种植地块高亮', filter);
            }
          });

        }
      });

      this.name = this.getQueryString('name');
      this.mj = this.getQueryString('mj');
    },

    methods: {
      initHeightAndFilter(){
        const  that=this;
        //定位种植地块
        if (that.getQueryString('x') && that.getQueryString('y')) {
          let x=that.getQueryString('x');
          let y=that.getQueryString('y');
          let bbox = [[x, y], [x, y]];
          let features = that.map.queryRenderedFeatures(bbox, {layers: ['种植地块点击']});
          if (features.length > 0) {
            let filter = features.reduce(function(memo, feature) {
              memo.push(feature.properties.objectid);
              return memo;
            }, ['in', 'objectid']);
            let coordinates = features[0].geometry.coordinates[0];
            let lngMin = coordinates[0][0];
            let lngMax = coordinates[0][0];
            let latMin = coordinates[0][1];
            let latMax = coordinates[0][1];
            for (let i = 1; i < coordinates.length; i++) {
              if (lngMin > coordinates[i][0]) {
                lngMin = coordinates[i][0];
              } else if (lngMax < coordinates[i][0]) {
                lngMax = coordinates[i][0];
              }
              if (latMin > coordinates[i][1]) {
                latMin = coordinates[i][1];
              } else if (lngMax < coordinates[i][1]) {
                latMax = coordinates[i][1];
              }
            }

            that.map.fitBounds(new mapboxgl.LngLatBounds([lngMin, latMin], [lngMax, latMax]), {
              padding: 60
            });


            that.id = features[0].properties.objectid;
            console.log(features[0].properties);
            that.qhmc = features[0].properties.qhmc;
            that.zwmc = features[0].properties.zwmc;
            that.map.setFilter('种植地块高亮', filter);
          }
        }else if( that.getQueryString('name')){
          API.getDkByName({
            qhdm:that.getQueryString('qhdm'),
            id:that.getQueryString('id'),
            name:that.getQueryString('name'),
          }).then(res=>{
            let filter=['in','dkbm'];
            if(res.data.length>0){
              for (let i = 0; i < res.data.length; i++) {
                filter.push(res.data[i].dkbm);
              }
              that.map.setFilter('种植地块高亮', filter);
            }
            console.log(res)
          }).catch(err=>{

          })
        }
      },

      /**
       * 添加控件
       */
      addControl: function() {
        let scale = new mapboxgl.ScaleControl({
          maxWidth: 80,
          unit: 'imperial'
        });
        this.map.addControl(scale);
        // this.map.addControl(new mapboxgl.FullscreenControl({container: document.querySelector('body')}));
      },
      click: function() {
        this.showInfo = false;
        this.map.setFilter('种植结构高亮', ['in', 'objectid', '']);
      },
      returnClick: function() {
        wx.miniProgram.navigateBack({delta: 1});
        // wx.miniProgram.navigateTo({
        //   url: '../login/login'
        // })
      },
      getQueryString: function(variable) {
        let url = decodeURI(window.location.href);
        if (url.indexOf('?') == -1) {
          return;
        }
        let array = url.split('?');
        var query = array[1];
        var vars = query.split('&');
        for (var i = 0; i < vars.length; i++) {
          var pair = vars[i].split('=');
          if (pair[0] == variable) {
            return pair[1];
          }
        }
        return (false);
      },
      /**
       * 根据区划代码定位行政区
       */
      locateXzqByQhdm(qhdm,  options = {padding: 60}) {
        const that =this;
        let map = this.map;
        API.getEnvByadmin({'qhdm': qhdm}).then(res => {
          if (res.code !== 0 || res.data.length <= 0 || !res.data[0].env) {
            that.$confirm('无法获取村信息', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            });
            return;
          }
          let env = JSON.parse(res.data[0].env);
          let e_bound = turf(env);
          let bounds = new mapboxgl.LngLatBounds(new mapboxgl.LngLat(e_bound[0], e_bound[1]), new mapboxgl.LngLat(e_bound[2], e_bound[3]));
          options.maxZoom = options.maxZoom || (this.getCurXzqInfo(qhdm).maxzoom - 0.1);
          map.fitBounds(bounds, options,{moveend:"111"});
        }).catch(err => {
          console.log(err.message);
        });
      },
      /**
       * 根据区划代码查询行政区级别
       */
      getCurXzqInfo(areaCode) {
        let curxzq = '';
        if (areaCode.length == 1) {
          curxzq = '全国';
        }
        if (areaCode.length == 2) {
          curxzq = '省';
        }
        if (areaCode.length == 4) {
          curxzq = '地市';
        }
        if (areaCode.length == 6) {
          curxzq = '县';
        }
        if (areaCode.length == 9) {
          curxzq = '乡镇';
        }
        if (areaCode.length == 12) {
          curxzq = '村';
        }
        return layerSrc.layer_Drilldown.find(item => {
          return item.levelName === curxzq;
        });
      }
    }
  };
</script>

<style>
  #map, .parent {
    width: 100%;
    height: 100%;
  }

  #map {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
  }

  .parent .card {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1000;
    /*width: 30%;*/
  }

  .top {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1000;
    width: 100%;
    height: 30px;
    background-color: rgba(0, 0, 0, 0.1);
    color: white;
    padding-left: 5px;
  }
</style>
